document.addEventListener('DOMContentLoaded', () => {
    const game = new Game('game-canvas');

    // 开始游戏按钮
    document.getElementById('start-btn').addEventListener('click', () => {
        document.getElementById('game-canvas').style.display = 'block';
        document.getElementById('score-display').style.display = 'block';
        document.getElementById('start-screen').style.display = 'none';
        game.start();
    });

    // 重新开始游戏
    document.getElementById('restart-btn').addEventListener('click', () => {
        document.getElementById('game-over').style.display = 'none';
        game.start();
    });

    // 难度选择
    const difficultyOptions = document.querySelectorAll('.difficulty-option');
    difficultyOptions.forEach(option => {
        option.addEventListener('click', function () {
            difficultyOptions.forEach(opt => opt.classList.remove('selected'));
            this.classList.add('selected');
            game.setSpeed(parseInt(this.dataset.speed));
        });
    });

    // 键盘控制
    document.addEventListener('keydown', event => {
        if (!game.gameRunning) return;

        switch (event.key) {
            case 'ArrowUp':
                if (game.snake.direction.y === 0) {
                    game.snake.changeDirection({ x: 0, y: -1 });
                }
                break;
            case 'ArrowDown':
                if (game.snake.direction.y === 0) {
                    game.snake.changeDirection({ x: 0, y: 1 });
                }
                break;
            case 'ArrowLeft':
                if (game.snake.direction.x === 0) {
                    game.snake.changeDirection({ x: -1, y: 0 });
                }
                break;
            case 'ArrowRight':
                if (game.snake.direction.x === 0) {
                    game.snake.changeDirection({ x: 1, y: 0 });
                }
                break;
        }
    });
});